package com.atom.module.mvvm.livedata

import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean

open class SingleLiveData<T> : MutableLiveData<T> {

    private val mPending = AtomicBoolean(false)

    constructor() : super()

    constructor(value: T) : super(value)

    @MainThread
    override fun observe(
        owner: LifecycleOwner, observer: Observer<in T>
    ) {
        super.observe(owner) { t ->
            if (mPending.compareAndSet(true, false)) {
                observer.onChanged(t)
            }
        }
    }

    override fun postValue(value: T) {
        super.postValue(value)
    }

    override fun setValue(value: T) {
        if (value == getValue()) return
        mPending.set(true)
        super.setValue(value)
    }
}